package com.ajaxdemo.china;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import com.ajaxdemo.bean.Province;
import com.ajaxdemo.util.DbDao;

/**
 * Servlet implementation class China
 */
@WebServlet("/Province_json")
public class Province_json extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		String sql = "select provinceID, province from hat_province;";
		ResultSet rs = DbDao.queryDb(sql); // 从数据库中拿到所有province的结果集
		List<Province> list = new ArrayList<Province>();
		try {
			while (rs.next()) {
				list.add(new Province(rs.getString(1), rs.getString(2)));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//System.out.println(list);
		String json = JSONArray.fromObject(list).toString();
		//System.out.println(json);
		// System.out.println("[" + result.toString().substring(1) + "]");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter(); // 发送到客户端
		out.println(json);
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
